<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="format-detection" content="telephone=no"/>
    <meta name="format-detection" content="email=no"/>
    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0" name="viewport">
    <title>helloworld</title>
    <script src="./socket.io-1.4.5.js"></script>
    <script type="text/javascript" src="jquery.2.1.1.min.js"></script>
</head>
<body>
<h id="getnum"></h>
<div style="width: 500px;height: 500px;overflow: auto" id="messages" class="chatbox">

</div>
<div>
    <input type="text" id="sendtext">
    <input type="button" id="sendbutton" value="发送消息">
</div>
<div>
    <input type="text" id="sendname">
    <input type="button" id="sendbutton2" value="更改昵称">
</div>
<script>
    var socket =io.connect('http://192.168.2.52:3000');
    socket.on('connect', function(){
        socket.emit('authentication', {"username": "John", "password": "secret2"});
    });
    socket.on('unauthorized', function(err){
        console.log("There was an error with the authentication:", err.message);
        socket.disconnect();
    });
    var username='';
    socket.on('new',function(msgObj){
        username=msgObj.username;
        console.log(msgObj.onlineCount);
        $("#getnum").html('当前聊天室共'+msgObj.onlineCount+'人');
        $('#messages').append($("<div>").html("<p>欢迎"+msgObj.username+"来到聊天室</p>"));
    });
    socket.on('chat', function(msgObj){
        $('#messages').append($("<div>").html("<p>"+msgObj.username+"说："+msgObj.message+"</p>"));
        messages.scrollTop = messages.scrollHeight;
    });
    $("#sendbutton").on('click',function(){
        var text=$("#sendtext").val();
        if(text!=''){
            socket.emit('chat',{'username':username,'message':text});
            $("#sendtext").val('');
        }
    });
    $("#sendbutton2").on('click',function(){
        var text2=$("#sendname").val();
        if(text2!=''){
            socket.emit('changename',{'username':username,'message':text2});
            username=text2;
            $("#sendname").val('');
        }
    });
    socket.on('changename', function(msgObj){
        $('#messages').append($("<div>").html("<p>"+msgObj.username+"更名为"+msgObj.message+"</p>"));
        messages.scrollTop = messages.scrollHeight;
    });

</script>
</body>
</html>